import collections
import math
import os
import shutil
import pandas as pd
import torch
import torchvision
from torch import nn
from d2l import torch as d2l
import matplotlib.pyplot as plt

#@save
d2l.DATA_HUB['cifar10_tiny'] = (d2l.DATA_URL + 'kaggle_cifar10_tiny.zip',
                                '2068874e4b9a9f0fb07ebe0ad2b29754449ccacd')

# 如果使用完整的Kaggle竞赛的数据集，设置demo为False


data_dir = d2l.download_extract('cifar10_tiny')

def read_csv_labels(fname):
    with open(fname, 'r') as f:
        lines = f.readlines()[1:]
    tokens = [l.rstrip().split(',') for l in lines]
    return dict(((name,label) for name,label in tokens))

labels = read_csv_labels(os.path.join(data_dir,'trainLabels.csv'))

def copyfile(filename,target_dir):
    os.makedirs(target_dir,exist_ok=True)  # 在traget_dir位置创建一个文件夹，exist_ok=false 则文件夹存在有异常
    shutil.copy(filename,target_dir)   # 把文件复制到此目录下

def reorg_train_valid(data_dir,labels,valid_ratio):
    n = collections.Counter(labels.values()).most_common()[-1][1]
    n_valid_per_label = max(1,math.floor(n*valid_ratio))  # 验证集中每个类别的图片数
    label_count = {}
    for train_file in os.listdir(os.path.join(data_dir,'train')):
        label = labels[train_file.split('.')[0]]
        fname = os.path.join(data_dir,'train',train_file)
        copyfile(fname,os.path.join(data_dir,'train_valid_test','train_valid',label))
        if label not in label_count or label_count[label] < n_valid_per_label:
            copyfile(fname,os.path.join(data_dir,'train_valid_test','valid',label))
            label_count[label] = label_count.get(label,0) + 1 # 第一次为0 后边就没用了
        else:
            copyfile(fname,os.path.join(data_dir,'train_valid_test','train',label))
    return n_valid_per_label # 讲valid集每个类别的图片数返回

def reorg_test(data_dir):
    for test_file in os.listdir(os.path.join(data_dir,'test')):
        copyfile(os.path.join(data_dir,'test',test_file),os.path.join(data_dir,'train_valid_test','test','unknown'))

def reorg_cifar10_data(data_dir,valid_ratio):
    labels = read_csv_labels(os.path.join(data_dir,'trainLabels.csv'))
    reorg_train_valid(data_dir,labels,valid_ratio)
    reorg_test(data_dir)

batch_size = 128
valid_ratio = 0.1
reorg_cifar10_data(data_dir, valid_ratio)

transform_train = torchvision.transforms.Compose([
    torchvision.transforms.Resize(40),
    torchvision.transforms.RandomResizedCrop(32,scale=(0.64,1.0),ratio=(1.0,1.0)),
    torchvision.transforms.RandomHorizontalFlip(),
    torchvision.transforms.ToTensor(),
    torchvision.transforms.Normalize([0.4914,0.4822,0.4465],
                                     [0.2023,0.1994,0.2010])])

trainfrom_test = torchvision.transforms.Compose([
        torchvision.transforms.ToTensor(),
        torchvision.transforms.Normalize([0.4914, 0.4822, 0.4465],
                                         [0.2023, 0.1994, 0.2010])])

train_ds,train_valid_ds = [
    torchvision.datasets.ImageFolder(root=os.path.join(data_dir,'train_valid_test',folder),transform=transform_train)
    for folder in ['train','train_valid']]

valid_ds,test_ds = [torchvision.datasets.ImageFolder(root=os.path.join(data_dir,'train_valid_test',folder),transform=trainfrom_test)
for folder in ['valid','test']]

train_iter ,train_valid_iter =[
    torch.utils.data.DataLoader(dataset,batch_size=batch_size,shuffle=True,drop_last=True)
    for dataset in [train_ds,train_valid_ds]]

valid_iter= [
    torch.utils.data.DataLoader(valid_ds,batch_size=batch_size,shuffle=False,drop_last=True)]

test_iter = [
    torch.utils.data.DataLoader(test_ds,batch_size=batch_size,shuffle=False,drop_last=False)]

def get_net():
    num_classes = 10
    net = d2l.resnet18(num_classes,3)
    return net

loss = nn.CrossEntropyLoss(reduction='none')

def train(net,train_iter,valid_iter,num_epochs,lr,wd,devices,lr_period,lr_decay):
    trainer = torch.optim.SGD(net.parameters(),lr=lr,weight_decay=wd,momentum=0.9)
    scheduler = torch.optim.lr_scheduler.StepLR(trainer,lr_period,lr_decay)
    num_batches = len(train_iter)
    net = nn.DataParallel(net,device_ids=devices).to(devices[0])
    for epoch in range(num_epochs):
        net.train()
        metric = d2l.Accumulator(3)
        for i,(features,labels) in enumerate(train_iter):
            l,acc = d2l.train_ch13(net,features,labels,loss,trainer,devices)
            metric.add(l,acc,labels.shape[0])
        if valid_iter is not None:
            valid_acc = d2l.evaluate_accuracy(valid_iter,net)
        scheduler.step()
    measures = (f'train_loss{metric[0]/metric[2]:.3f}',f'train_acc{metric[1]/metric[2]:.3f}')
    if valid_iter is not None:
        measures += (f',valid_acc{valid_acc:.3f}')
    print(measures)

devices ,num_epochs,lr,wd =d2l.try_all_gpus(),20,2e-4,5e-4
lr_period,lr_decay = 4,0.9
net = get_net()
train(net,train_iter, valid_iter,num_epochs,lr, wd, devices, lr_period, lr_decay)



















